Imagine you are an architect. Instead of drawing a fixed plan for a single brick house, you design a master blueprint capable of adapting to wood, steel, or glass. In C++, this is Generic Programming.
1. The Blueprint Mechanism
A template parameter list (e.g., template <typename T>) introduces placeholders called template type parameters. These act as variables for types. For example, in template <typename T> ostream &print(ostream &os, const T &obj), T is determined only when the function is called.
2. Instantiation
The compiler does not compile the template itself into machine code. Instead, instantiation occurs: the compiler generates a specific version of the code only when a concrete template argument is provided. Because of this, definitions must typically reside in header files.
3. Writing Type-Independent Code
To maximize reusability, follow the Best Practice: minimize requirements. Writing the code using only the < operator (via less<T>) reduces the requirements on types compared to using >, <=, and >=. Validation is often delayed; the compiler generally can't find many errors at the stage of compiling the template itself; most appear during instantiation.